import json
import threading
import time
from datetime import datetime, timedelta
import requests
import socket

from dateutil.parser import parse


class PollingThread(threading.Thread):
    def __init__(self, name, user_id, url, control_url, socket_url, ue_url):
        super().__init__(name=name)
        self.user_id = user_id
        self.should_stop = False
        self.url = url
        self.control_url = control_url
        self.socket_url = socket_url
        self.ue_url = ue_url

        self.socket_url = self.socket_url.replace('http://', '')
        socket_list = self.socket_url.split(':')
        self.socket_address = socket_list[0]
        self.socket_port = socket_list[1]

        self.ue_url = self.ue_url.replace('http://', '')
        ue_list = self.ue_url.split(':')
        self.ue_address = ue_list[0]
        self.ue_port = ue_list[1]

    def run(self):
        try:
            awake_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            awake_socket.connect((self.socket_address, self.socket_port))
        except:
            pass
        try:
            ue_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            ue_socket.connect((self.ue_address, self.ue_port))
        except:
            pass
        count = 0
        data = []
        temper = [0.0, 0.0, 0.0]
        now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        while not self.should_stop:
            body = {
                "userid": self.user_id,
                "time": now
            }
            response = requests.post(url=self.url + '/operate/api/v1/healthinfo', json=body)
            heathinfo_list = json.loads(response.text)['data']
            try:
                if len(heathinfo_list) < 1:
                    continue
            except:
                continue
            raw_data = heathinfo_list[len(heathinfo_list) - 1]
            if float(raw_data['heart']) == 0:
                continue
            pressure = raw_data['pressure']
            if count == 0:
                temper[0] = 60000.0 / float(raw_data['heart'])
                count = count + 1
            elif count == 1:
                temper[1] = 60000.0 / float(raw_data['heart'])
                count = count + 1
            elif count == 2:
                temper[2] = 60000.0 / float(raw_data['heart'])
                count = 0
                data.append((sum(temper) / len(temper)))
                if len(data) >= 20:
                    response = requests.post(url=self.control_url + '/v1/hrv',
                                             json={"data": data})
                    res = response.text
                    pressure = json.loads(res)['data']['sdnn']
                    response = requests.post(url=self.url + '/operate/api/v1/savepressure',
                                             json={
                                                 "userid": self.user_id,
                                                 "pressure": pressure
                                             })
            eventName = 'archery'
            body = {
                "heart": raw_data['heart'],
                "pressure": pressure
            }
            message = json.dumps({"event": eventName, "data": body})
            try:
                ue_socket.send(message.encode('utf-8'))
            except:
                pass
            time.sleep(1)
        awake_socket.close()
        ue_socket.close()

    def stop(self):
        self.should_stop = True
